﻿using Shape.Events;
using Shape;
using Shape.Mvp.Sample.Commands;
using Shape.Mvp.Sample.Domain.Model;
using Shape.Mvp.Sample.Domain.Repositories;
using Shape.Mvp.Sample.Events;
using Shape.Mvp.Sample.Views;
using System;
using System.Diagnostics.Contracts;

namespace Shape.Mvp.Sample.Presenters
{
   public class ExerciseDetailPresenter : Presenter<IExerciseDetailView>,
														ISubscriber<PositionSelectedEvent>
   {
   #region Fields
		// Dependencies
      private IRepository<Exercise> _exerciseRepository;
		private IRepository<Position> _positionRepository;

		private Exercise _currentExercise;
   #endregion

   #region Constructor(s)
		public ExerciseDetailPresenter(
			IApplicationController applicationController,
			IRepository<Exercise> exerciseRepository,
			IRepository<Position> positionRepository,
			IExerciseDetailView view) : base(applicationController, view)
		{
			Contract.Requires(exerciseRepository != null);
			Contract.Requires(positionRepository != null);

			_exerciseRepository = exerciseRepository;
			_positionRepository = positionRepository;
		}
	#endregion

	#region Events
		void OnViewAccepted(object sender, EventArgs e)
		{
			if (!String.IsNullOrWhiteSpace(View.ExerciseName))
			{
				_currentExercise.Name = View.ExerciseName;

				View.CanClose = true;

				// Broadcast that the exercise has been updated
				ApplicationController.Publish<ExerciseUpdatedEvent>(new ExerciseUpdatedEvent(_currentExercise.Id));
			}
		}

		void OnViewShowPositionList()
		{
			ApplicationController.Execute<ShowPositionListCommand>();
		}
	#endregion

      public void Initialise(Guid id)
      {
			// Subscribe for application events
			ApplicationController.AddEventSubscriber(this);

         View.Accepted += OnViewAccepted;
			View.ShowPositionList += OnViewShowPositionList;

         _currentExercise = _exerciseRepository.GetById(id);

         if (_currentExercise != null)
         {
            View.ExerciseName = _currentExercise.Name;
            if (_currentExercise.StartingPosition != null)
            {
               View.StartingPosition = _currentExercise.StartingPosition.Description;
            }
				else
				{
					View.StartingPosition = string.Empty;
				}
				
         }
      }

		void ISubscriber<PositionSelectedEvent>.Handle(PositionSelectedEvent item)
		{
			_currentExercise.StartingPosition = _positionRepository.GetById(item.Id);

			View.StartingPosition = _currentExercise.StartingPosition.Description;	
		}
	}
}
